package com.example.avmanagerweb.Utils.EncryptionUtil;

import com.alibaba.fastjson.JSONObject;

import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.Map;

public class MD5Util {
    //做秘钥
    private final static String VIP = "e-YHR:";

    public static String stringToMD5(String plainText) {
        byte[] secretBytes = null;
        try {
            secretBytes = MessageDigest.getInstance("md5").digest(
                    plainText.getBytes("UTF-8"));
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("没有这个md5算法！");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        String md5code = new BigInteger(1, secretBytes).toString(16);
        for (int i = 0; i < 32 - md5code.length(); i++) {
            md5code = "0" + md5code;
        }
        return md5code;
    }

    public static String oneEncrypt( String s) {
        //去除字符符号
        String s1 = s.replace("\\", "");
        String s2 = s1.replace("{", "");
        String s3 = s2.replace("}", "");
        String s4 = s3.replace("\"", "");
        String s5 = s4.replace(":", "");
        String s6 = s5.replace(",", "");
        //做秘钥
//        String VIP="e-YHR:";
        String s6Vip = s6 + VIP;
        //全部转大写
        String s7 = s6Vip.toUpperCase();
        //排序小到打
        char[] chars = s7.toCharArray();
        //排序小到大
        Arrays.sort(chars);
        String s8 = new String(chars);

        //MD5加密
        String s9 = MD5Util.stringToMD5(s8);
        System.out.println(s8);
        System.out.println(s9);
        return s9;
    }

    /**
     *
     * @param fileCondition json
     * @param privateKey    秘钥
     * @return
     */

    public static String oneEncrypt(Map<String,String> fileCondition, String privateKey) {
        JSONObject json = (JSONObject) JSONObject.toJSON(fileCondition);
        String s = json.toJSONString();
        //去除字符符号
        String s1 = s.replace("\\", "");
        String s2 = s1.replace("{", "");
        String s3 = s2.replace("}", "");
        String s4 = s3.replace("\"", "");
        String s5 = s4.replace(":", "");
        String s6 = s5.replace(",", "");
        //做秘钥
//        String VIP="e-YHR:";
        String s6Vip = s6 + privateKey;
        //全部转大写
        String s7 = s6Vip.toUpperCase();
        //排序小到打
        char[] chars = s7.toCharArray();
        //排序小到大
        Arrays.sort(chars);
        String s8 = new String(chars);
        System.out.println(s8);
        //MD5加密
        String s9 = MD5Util.stringToMD5(s8);
        System.out.println(s9);
        return s9;
    }



}
